<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./three.min.js"></script>
    <script src="./OrbitControls.js"></script>
</head>

<body>
    <div></div>
    <script>

        const scene = new THREE.Scene()
        //相机
        const camara = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
        camara.position.set(0, 0, 10)
        //几何体
        const cube = new THREE.Mesh(
            new THREE.BoxGeometry(2, 2, 2),
            new THREE.MeshBasicMaterial({ color: "#f90" })
        )
        scene.add(cube)

        //渲染器
        const renderder = new THREE.WebGLRenderer({
            antialias: true
        })
        renderder.setSize(window.innerWidth, window.innerHeight)
        renderder.setClearColor("#ccc")
        document.body.appendChild(renderder.domElement)


        const loader = new THREE.FontLoader();
        loader.load('/helvetiker_regular.typeface.json', function (font) {
            const geometry = new THREE.TextGeometry('Hello World', {
                font: font,
                size: 1,
                height: 0.1
            });
            geometry.center(); // 居中几何体
            const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
            const text = new THREE.Mesh(geometry, material);
            text.position.set(0, 10, 0);
            scene.add(text);
        });


        //控制器
        const control = new THREE.OrbitControls(camara, renderder.domElement)
        //渲染函数
        const render = () => {
            renderder.render(scene, camara)
            requestAnimationFrame(render)
        }
        render()
        const mouse = new THREE.Vector2()
        let rayCaster = new THREE.Raycaster()
        const handlerClick = (e) => {
            // let dom=scene.children[1]
            // scene.children[1].position.set(0, 100, 0);

            mouse.x = (e.clientX / window.innerWidth) * 2 - 1  //通过web中鼠标坐标得到标准屏幕坐标
            mouse.y = -(e.clientY / window.innerHeight) * 2 + 1
            rayCaster.setFromCamera(mouse, camara)  //// 通过摄像机和鼠标位置更新射线

            let intersects = rayCaster.intersectObjects(scene.children) //获取场景中所有与射线相交的物体，结果是一个数组
            console.log("intersects:", intersects)

            if (intersects.length > 0) { //length>0则说明有与射线相交的问题。表明点击了
                console.log(intersects[0])
                let poin1=intersects[0].point;
                scene.children[1].position.set(poin1.x, poin1.y, poin1.z)
            }
        }
        window.addEventListener("click", handlerClick)
    </script>

</body>

</html>